import axios from 'axios';
import common from '../public/sha512';
import qs from 'qs';
let http = axios.create({
	//headers: {'Content-Type': 'application/x-www-form-urlencoded'},
	timeout: 20000, //延时
});
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
http.defaults.headers.get['Content-Type'] = 'application/json; charset=utf-8'
http.interceptors.request.use( //请求参数设置
	config => {
		// console.log(config)
		if (config.method === 'post' || config.method === 'put') {
			// post、put 提交时，将对象转换为string, 为处理Java后台解析问题
			var timestamp = new Date().format("yyyy-MM-dd hh");
			var userinfo = JSON.parse(localStorage.getItem('userinfo'));
			if ((typeof config.data) == 'string') {
				var data = JSON.parse(config.data);
				if (userinfo && (typeof userinfo.userID !== 'undefined')) {
					data.userID = userinfo.userID;
				};
				var param = JSON.stringify(data);
			} else if ((typeof config.data) == 'object') {
				if (userinfo && (typeof userinfo.userID !== 'undefined')) {
					config.data.userID = userinfo.userID;
				};
				var param = JSON.stringify(config.data);
			};
			var sign = common.hexsha512(param + timestamp);
			//java只接受字符串   解析的俩种方式
			//config.data = "param=" + param + "&sign=" + sign;  //1字符串拼接
			config.data = qs.stringify({
				param,
				sign
			}); //2对象编码
		} else if (config.method === 'get') {
			// 给GET 请求后追加时间戳， 解决IE GET 请求缓存问题
			var timestamp = new Date().format("yyyy-MM-dd hh");
			var userinfo = JSON.parse(localStorage.getItem('userinfo'));
			// console.log((typeof config.params))
			if ((typeof config.params) == 'string') {
				var param = JSON.parse(config.params);
				if (userinfo && (typeof userinfo.userID !== 'undefined')) {
					param.userID = userinfo.userID;
				};
				param = JSON.stringify(param);
			} else if ((typeof config.params) == 'object') {
				if (userinfo && (typeof userinfo.userID !== 'undefined')) {
					config.params.userID = userinfo.userID;
				};
				var param = JSON.stringify(config.params);
			}
			// console.log(param)
			var sign = common.hexsha512(param + timestamp);
			config.params = {
				param: param,
				sign: sign
			}
		};
		return config
	},
	err => {
		return Promise.reject(err)
	})
http.interceptors.response.use( //响应请求
	config => {
		return config
	},
	err => {
		return Promise.reject(err)
	})

export default {
	get(url, params, headers) {
		let options = {};
		params && (options.params = params);
		headers && (options.headers = headers);
		return http.get(url, options);
	},
	post(url, params, headers) {
		let options = {};
		headers && (options.headers = headers);
		return http.post(url, params, options);
	},
	put(url, params, headers) {
		let options = {};
		headers && (options.headers = headers);
		return http.put(url, params, options);
	},
	delete(url, params, headers) {
		let options = {};
		params && (options.params = params);
		headers && (options.headers = headers);
		return http.delete(url, options);
	}
};